{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Machine Learning Estratégico para Finanzas: Modelos de Predicción y Herramientas de Control de Riesgo"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Autor(es) Willay Solutions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 295104 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {
      "image/png": {
       "width": 800
      }
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "display(Image(filename='Info Willay.png', width=800))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### RESUMEN EJECUTIVO"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Este caso de estudio muestra cómo la aplicación de métodos avanzados de machine learning puede transformar la gestión financiera al mejorar la precisión en la predicción de mercados, optimizar la calificación crediticia y robustecer los esquemas de control de riesgo. A través de diferentes modelos y técnicas (desde árboles de regresión y random forests hasta simulaciones de Montecarlo y análisis de valor en riesgo, VaR), se lograron hallazgos que potencialmente impulsan la toma de decisiones estratégicas en instituciones financieras y organizaciones que buscan un enfoque analítico de vanguardia.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### OBJETIVOS CLAVE"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Analizar el impacto de indicadores macroeconómicos (IPC, M2, tasa de la Fed) en el comportamiento de activos bursátiles.Optimizar la evaluación crediticia mediante modelos de clasificación (regresión logística y discriminante lineal).\n",
    "2. Fortalecer la gestión del riesgo de mercado en un activo de referencia (ETF SPY) mediante técnicas de simulación y modelos que capturan cambios de régimen en la volatilidad.\n",
    "3. Explorar la relación entre los tipos de interés y el rendimiento de un índice clave (SPY), incluyendo enfoques avanzados como las regresiones cuántiles."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Primera parte: Análisis económico-financiero de Variables macroeconómicas de USA"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Enfoque y metodología"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Descripción: Se emplearon datos de IPC, masa monetaria (M2) y la tasa de la Fed para construir modelos que estimaran la dinámica de un índice bursátil."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Herramientas empleadas:\n",
    "Test SDF (Stochastic Discount Factor) para examinar la interrelación entre variables macro y precios de activos.\n",
    "Árboles de Decisión y Random Forest para capturar relaciones no lineales y mejorar la exactitud de las proyecciones."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Principales logros:\n",
    "Se consiguió un incremento del 10% en el nivel de precisión al comparar el random forest con el árbol de regresión.\n",
    "La tasa de la Fed y M2 destacaron como factores determinantes, evidenciando su impacto directo en el comportamiento del mercado."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from statsmodels.tsa.stattools import adfuller\n",
    "from sklearn.preprocessing import StandardScaler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>DATE</th>\n",
       "      <th>cpi</th>\n",
       "      <th>wti</th>\n",
       "      <th>unempoyment</th>\n",
       "      <th>cons_sent</th>\n",
       "      <th>m2</th>\n",
       "      <th>fed_funds</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1/1/1988</td>\n",
       "      <td>115.700</td>\n",
       "      <td>17.129500</td>\n",
       "      <td>0.057</td>\n",
       "      <td>90.8</td>\n",
       "      <td>2847.4</td>\n",
       "      <td>0.0683</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2/1/1988</td>\n",
       "      <td>116.000</td>\n",
       "      <td>16.795714</td>\n",
       "      <td>0.057</td>\n",
       "      <td>91.6</td>\n",
       "      <td>2870.4</td>\n",
       "      <td>0.0658</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3/1/1988</td>\n",
       "      <td>116.500</td>\n",
       "      <td>16.197391</td>\n",
       "      <td>0.057</td>\n",
       "      <td>94.6</td>\n",
       "      <td>2890.7</td>\n",
       "      <td>0.0658</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4/1/1988</td>\n",
       "      <td>117.100</td>\n",
       "      <td>17.862500</td>\n",
       "      <td>0.054</td>\n",
       "      <td>91.2</td>\n",
       "      <td>2910.7</td>\n",
       "      <td>0.0687</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5/1/1988</td>\n",
       "      <td>117.500</td>\n",
       "      <td>17.423636</td>\n",
       "      <td>0.056</td>\n",
       "      <td>94.8</td>\n",
       "      <td>2926.0</td>\n",
       "      <td>0.0709</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>434</th>\n",
       "      <td>3/1/2024</td>\n",
       "      <td>312.332</td>\n",
       "      <td>81.278000</td>\n",
       "      <td>0.038</td>\n",
       "      <td>79.4</td>\n",
       "      <td>20835.8</td>\n",
       "      <td>0.0533</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>435</th>\n",
       "      <td>4/1/2024</td>\n",
       "      <td>313.548</td>\n",
       "      <td>85.347273</td>\n",
       "      <td>0.039</td>\n",
       "      <td>77.2</td>\n",
       "      <td>20861.4</td>\n",
       "      <td>0.0533</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>436</th>\n",
       "      <td>5/1/2024</td>\n",
       "      <td>314.069</td>\n",
       "      <td>80.024545</td>\n",
       "      <td>0.040</td>\n",
       "      <td>69.1</td>\n",
       "      <td>20951.8</td>\n",
       "      <td>0.0533</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>437</th>\n",
       "      <td>6/1/2024</td>\n",
       "      <td>314.175</td>\n",
       "      <td>79.767368</td>\n",
       "      <td>0.041</td>\n",
       "      <td>68.2</td>\n",
       "      <td>21025.1</td>\n",
       "      <td>0.0533</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>438</th>\n",
       "      <td>7/1/2024</td>\n",
       "      <td>314.540</td>\n",
       "      <td>81.800455</td>\n",
       "      <td>0.043</td>\n",
       "      <td>66.4</td>\n",
       "      <td>21054.4</td>\n",
       "      <td>0.0533</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>439 rows × 7 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "         DATE      cpi        wti  unempoyment  cons_sent       m2  fed_funds\n",
       "0    1/1/1988  115.700  17.129500        0.057       90.8   2847.4     0.0683\n",
       "1    2/1/1988  116.000  16.795714        0.057       91.6   2870.4     0.0658\n",
       "2    3/1/1988  116.500  16.197391        0.057       94.6   2890.7     0.0658\n",
       "3    4/1/1988  117.100  17.862500        0.054       91.2   2910.7     0.0687\n",
       "4    5/1/1988  117.500  17.423636        0.056       94.8   2926.0     0.0709\n",
       "..        ...      ...        ...          ...        ...      ...        ...\n",
       "434  3/1/2024  312.332  81.278000        0.038       79.4  20835.8     0.0533\n",
       "435  4/1/2024  313.548  85.347273        0.039       77.2  20861.4     0.0533\n",
       "436  5/1/2024  314.069  80.024545        0.040       69.1  20951.8     0.0533\n",
       "437  6/1/2024  314.175  79.767368        0.041       68.2  21025.1     0.0533\n",
       "438  7/1/2024  314.540  81.800455        0.043       66.4  21054.4     0.0533\n",
       "\n",
       "[439 rows x 7 columns]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Cargar el dataset\n",
    "data = pd.read_csv('series.csv')\n",
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Se crea una copia del dataset a la cual se le aplicará la transformación logarítmica\n",
    "log_data = data.copy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Se itera sobre las columnas para aplicar el logaritmo\n",
    "for column in log_data.columns[1:]:\n",
    "    log_data[column] = log_data[column].apply(lambda x: np.log(x) if x > 0 else np.nan) # Se aplica el logaritmo a los valores mayores a 0\n",
    "\n",
    "log_data = log_data.dropna() # Se eliminan los valores nulos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Se realiza el test ADF para cada variable\n",
    "adf_results = {}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Realizar el test ADF para cada variable con constante y tendencia\n",
    "adf_results_ct = {}\n",
    "for column in log_data.columns[1:]:\n",
    "    adf_test_ct = adfuller(log_data[column], regression='ct', autolag='AIC')\n",
    "    adf_results_ct[column] = {\n",
    "        'ADF Statistic': adf_test_ct[0],\n",
    "        'p-value': adf_test_ct[1],\n",
    "        'Critical Values': adf_test_ct[4]\n",
    "    }\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Resultados del test ADF con constante y tendencia:\n",
      "Resultados del test ADF para cpi:\n",
      "  ADF Statistic: -2.824719288973276\n",
      "  p-value: 0.18801352633819107\n",
      "  1%: -3.9801797925777533\n",
      "  5%: -3.420846481913515\n",
      "  10%: -3.133141401260835\n",
      "\n",
      "\n",
      "Resultados del test ADF para wti:\n",
      "  ADF Statistic: -3.0717380526285463\n",
      "  p-value: 0.11311512492833486\n",
      "  1%: -3.9796851549477847\n",
      "  5%: -3.4206078061022183\n",
      "  10%: -3.1330011927146035\n",
      "\n",
      "\n",
      "Resultados del test ADF para unempoyment:\n",
      "  ADF Statistic: -2.9256632649808565\n",
      "  p-value: 0.15406277541460767\n",
      "  1%: -3.9796369453725298\n",
      "  5%: -3.4205845422066594\n",
      "  10%: -3.1329875260529962\n",
      "\n",
      "\n",
      "Resultados del test ADF para cons_sent:\n",
      "  ADF Statistic: -2.366310610803197\n",
      "  p-value: 0.3976756045625183\n",
      "  1%: -3.9799295833598074\n",
      "  5%: -3.420725752801191\n",
      "  10%: -3.1330704807562086\n",
      "\n",
      "\n",
      "Resultados del test ADF para m2:\n",
      "  ADF Statistic: -3.1467297484088532\n",
      "  p-value: 0.09554839349413241\n",
      "  1%: -3.9800790021304353\n",
      "  5%: -3.420797850107098\n",
      "  10%: -3.133112833488294\n",
      "\n",
      "\n",
      "Resultados del test ADF para fed_funds:\n",
      "  ADF Statistic: -2.111197383197558\n",
      "  p-value: 0.5398209448981075\n",
      "  1%: -3.9798311295958153\n",
      "  5%: -3.420678245656216\n",
      "  10%: -3.133042572822471\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Mostrar los resultados con constante y tendencia\n",
    "print(\"Resultados del test ADF con constante y tendencia:\")\n",
    "for column, result in adf_results_ct.items():\n",
    "    print(f\"Resultados del test ADF para {column}:\")\n",
    "    print(f\"  ADF Statistic: {result['ADF Statistic']}\")\n",
    "    print(f\"  p-value: {result['p-value']}\")\n",
    "    for key, value in result['Critical Values'].items():\n",
    "        print(f\"  {key}: {value}\")\n",
    "    print(\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sólo la oferta monetaria (M2)puede ser considerada como estacionaria al tomar en cuenta la constante y tendencia, sin embargo esto sólo se puede afirmar con el 90% de confianza; dada la naturaleza de la variable, no se la considerará como estacionaria o integrada de orden 0. Ninguna de las demás variables es estacionaria al realizar la prueba ADF con constante y tendencia."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Realizar el test ADF para cada variable sin constante ni tendencia\n",
    "adf_results_nc = {}\n",
    "for column in log_data.columns[1:]:\n",
    "    adf_test_nc = adfuller(log_data[column], regression='n', autolag='AIC')\n",
    "    adf_results_nc[column] = {\n",
    "        'ADF Statistic': adf_test_nc[0],\n",
    "        'p-value': adf_test_nc[1],\n",
    "        'Critical Values': adf_test_nc[4]\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Resultados del test ADF sin constante ni tendencia:\n",
      "Resultados del test ADF para cpi:\n",
      "  ADF Statistic: 3.456545960230612\n",
      "  p-value: 0.9999889662239263\n",
      "  1%: -2.5710207861591696\n",
      "  5%: -1.941650223026257\n",
      "  10%: -1.6162097540207612\n",
      "\n",
      "\n",
      "Resultados del test ADF para wti:\n",
      "  ADF Statistic: 0.4819480114290086\n",
      "  p-value: 0.8207012443516565\n",
      "  1%: -2.5709108689927582\n",
      "  5%: -1.9416363771666616\n",
      "  10%: -1.6162221170422162\n",
      "\n",
      "\n",
      "Resultados del test ADF para unempoyment:\n",
      "  ADF Statistic: -0.04729769242166674\n",
      "  p-value: 0.6683238932354771\n",
      "  1%: -2.5708870614847235\n",
      "  5%: -1.94163337991128\n",
      "  10%: -1.6162247966589938\n",
      "\n",
      "\n",
      "Resultados del test ADF para cons_sent:\n",
      "  ADF Statistic: -0.5597034140044327\n",
      "  p-value: 0.4714342387706495\n",
      "  1%: -2.570946996086369\n",
      "  5%: -1.9416409265499461\n",
      "  10%: -1.6162180520712746\n",
      "\n",
      "\n",
      "Resultados del test ADF para m2:\n",
      "  ADF Statistic: 4.420320054264909\n",
      "  p-value: 0.9999999994813645\n",
      "  1%: -2.5709228555275243\n",
      "  5%: -1.9416378864437647\n",
      "  10%: -1.6162207681657739\n",
      "\n",
      "\n",
      "Resultados del test ADF para fed_funds:\n",
      "  ADF Statistic: -0.6857026865815253\n",
      "  p-value: 0.41863288875665916\n",
      "  1%: -2.5709228555275243\n",
      "  5%: -1.9416378864437647\n",
      "  10%: -1.6162207681657739\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Mostrar los resultados sin constante ni tendencia\n",
    "print(\"Resultados del test ADF sin constante ni tendencia:\")\n",
    "for column, result in adf_results_nc.items():\n",
    "    print(f\"Resultados del test ADF para {column}:\")\n",
    "    print(f\"  ADF Statistic: {result['ADF Statistic']}\")\n",
    "    print(f\"  p-value: {result['p-value']}\")\n",
    "    for key, value in result['Critical Values'].items():\n",
    "        print(f\"  {key}: {value}\")\n",
    "    print(\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ninguna de las variables es estacionaria al dejar detener en cuenta la constante y la tendencia."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Se proecede a realizar las pruebas ADF para la primera diferencia de las variables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>DATE</th>\n",
       "      <th>cpi</th>\n",
       "      <th>wti</th>\n",
       "      <th>unempoyment</th>\n",
       "      <th>cons_sent</th>\n",
       "      <th>m2</th>\n",
       "      <th>fed_funds</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2/1/1988</td>\n",
       "      <td>0.002590</td>\n",
       "      <td>-0.019678</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.008772</td>\n",
       "      <td>0.008045</td>\n",
       "      <td>-0.037290</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3/1/1988</td>\n",
       "      <td>0.004301</td>\n",
       "      <td>-0.036274</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.032226</td>\n",
       "      <td>0.007047</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4/1/1988</td>\n",
       "      <td>0.005137</td>\n",
       "      <td>0.097853</td>\n",
       "      <td>-0.054067</td>\n",
       "      <td>-0.036603</td>\n",
       "      <td>0.006895</td>\n",
       "      <td>0.043129</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5/1/1988</td>\n",
       "      <td>0.003410</td>\n",
       "      <td>-0.024876</td>\n",
       "      <td>0.036368</td>\n",
       "      <td>0.038715</td>\n",
       "      <td>0.005243</td>\n",
       "      <td>0.031521</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>6/1/1988</td>\n",
       "      <td>0.004246</td>\n",
       "      <td>-0.052788</td>\n",
       "      <td>-0.036368</td>\n",
       "      <td>-0.001055</td>\n",
       "      <td>0.004229</td>\n",
       "      <td>0.057550</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>434</th>\n",
       "      <td>3/1/2024</td>\n",
       "      <td>0.006443</td>\n",
       "      <td>0.050841</td>\n",
       "      <td>-0.025975</td>\n",
       "      <td>0.031992</td>\n",
       "      <td>0.004420</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>435</th>\n",
       "      <td>4/1/2024</td>\n",
       "      <td>0.003886</td>\n",
       "      <td>0.048853</td>\n",
       "      <td>0.025975</td>\n",
       "      <td>-0.028099</td>\n",
       "      <td>0.001228</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>436</th>\n",
       "      <td>5/1/2024</td>\n",
       "      <td>0.001660</td>\n",
       "      <td>-0.064395</td>\n",
       "      <td>0.025318</td>\n",
       "      <td>-0.110845</td>\n",
       "      <td>0.004324</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>437</th>\n",
       "      <td>6/1/2024</td>\n",
       "      <td>0.000337</td>\n",
       "      <td>-0.003219</td>\n",
       "      <td>0.024693</td>\n",
       "      <td>-0.013110</td>\n",
       "      <td>0.003492</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>438</th>\n",
       "      <td>7/1/2024</td>\n",
       "      <td>0.001161</td>\n",
       "      <td>0.025168</td>\n",
       "      <td>0.047628</td>\n",
       "      <td>-0.026748</td>\n",
       "      <td>0.001393</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>438 rows × 7 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "         DATE       cpi       wti  unempoyment  cons_sent        m2  fed_funds\n",
       "1    2/1/1988  0.002590 -0.019678     0.000000   0.008772  0.008045  -0.037290\n",
       "2    3/1/1988  0.004301 -0.036274     0.000000   0.032226  0.007047   0.000000\n",
       "3    4/1/1988  0.005137  0.097853    -0.054067  -0.036603  0.006895   0.043129\n",
       "4    5/1/1988  0.003410 -0.024876     0.036368   0.038715  0.005243   0.031521\n",
       "5    6/1/1988  0.004246 -0.052788    -0.036368  -0.001055  0.004229   0.057550\n",
       "..        ...       ...       ...          ...        ...       ...        ...\n",
       "434  3/1/2024  0.006443  0.050841    -0.025975   0.031992  0.004420   0.000000\n",
       "435  4/1/2024  0.003886  0.048853     0.025975  -0.028099  0.001228   0.000000\n",
       "436  5/1/2024  0.001660 -0.064395     0.025318  -0.110845  0.004324   0.000000\n",
       "437  6/1/2024  0.000337 -0.003219     0.024693  -0.013110  0.003492   0.000000\n",
       "438  7/1/2024  0.001161  0.025168     0.047628  -0.026748  0.001393   0.000000\n",
       "\n",
       "[438 rows x 7 columns]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Función para calcular diferencias\n",
    "def calculate_differences(df):\n",
    "    diff_data = df.copy()\n",
    "    for column in df.columns[1:]:\n",
    "        diff_data[column] = df[column].diff()\n",
    "    return diff_data.dropna()\n",
    "\n",
    "# Calcular las diferencias\n",
    "diff_data = calculate_differences(log_data)\n",
    "diff_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Resultados del test ADF con constante y tendencia (diferencias):\n",
      "Resultados del test ADF para cpi:\n",
      "  ADF Statistic: -4.129065926132317\n",
      "  p-value: 0.005714887671256216\n",
      "  1%: -3.9802305462080194\n",
      "  5%: -3.420870970310604\n",
      "  10%: -3.133155786346428\n",
      "\n",
      "\n",
      "Resultados del test ADF para wti:\n",
      "  ADF Statistic: -11.629524235447116\n",
      "  p-value: 1.6001408343909272e-18\n",
      "  1%: -3.9797822454973732\n",
      "  5%: -3.420654657076956\n",
      "  10%: -3.1330287156598158\n",
      "\n",
      "\n",
      "Resultados del test ADF para unempoyment:\n",
      "  ADF Statistic: -15.044417240286174\n",
      "  p-value: 2.0799615979893338e-22\n",
      "  1%: -3.9796851549477847\n",
      "  5%: -3.4206078061022183\n",
      "  10%: -3.1330011927146035\n",
      "\n",
      "\n",
      "Resultados del test ADF para cons_sent:\n",
      "  ADF Statistic: -9.811801441383142\n",
      "  p-value: 5.8215421032438126e-15\n",
      "  1%: -3.9799295833598074\n",
      "  5%: -3.420725752801191\n",
      "  10%: -3.1330704807562086\n",
      "\n",
      "\n",
      "Resultados del test ADF para m2:\n",
      "  ADF Statistic: -5.871478767955748\n",
      "  p-value: 4.074105880366893e-06\n",
      "  1%: -3.9798311295958153\n",
      "  5%: -3.420678245656216\n",
      "  10%: -3.133042572822471\n",
      "\n",
      "\n",
      "Resultados del test ADF para fed_funds:\n",
      "  ADF Statistic: -7.359825413456292\n",
      "  p-value: 2.1388963061991932e-09\n",
      "  1%: -3.9798311295958153\n",
      "  5%: -3.420678245656216\n",
      "  10%: -3.133042572822471\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#Se vuelven a realizar los tests ADF con constante y tendencia para las series diferenciadas\n",
    "\n",
    "adf_results_diff_ct = {}\n",
    "for column in diff_data.columns[1:]:\n",
    "    adf_test_diff_ct = adfuller(diff_data[column], regression='ct', autolag='AIC')\n",
    "    adf_results_diff_ct[column] = {\n",
    "        'ADF Statistic': adf_test_diff_ct[0],\n",
    "        'p-value': adf_test_diff_ct[1],\n",
    "        'Critical Values': adf_test_diff_ct[4]\n",
    "    }\n",
    "\n",
    "print(\"Resultados del test ADF con constante y tendencia (diferencias):\")\n",
    "for column, result in adf_results_diff_ct.items():\n",
    "    print(f\"Resultados del test ADF para {column}:\")\n",
    "    print(f\"  ADF Statistic: {result['ADF Statistic']}\")\n",
    "    print(f\"  p-value: {result['p-value']}\")\n",
    "    for key, value in result['Critical Values'].items():\n",
    "        print(f\"  {key}: {value}\")\n",
    "    print(\"\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Resultados del test ADF sin constante ni tendencia (diferencias):\n",
      "Resultados del test ADF para cpi:\n",
      "  ADF Statistic: -2.107354655072591\n",
      "  p-value: 0.033642117859606156\n",
      "  1%: -2.571008342921378\n",
      "  5%: -1.9416486549547751\n",
      "  10%: -1.616211152880237\n",
      "\n",
      "\n",
      "Resultados del test ADF para wti:\n",
      "  ADF Statistic: -11.62157093052778\n",
      "  p-value: 3.91795727064723e-21\n",
      "  1%: -2.5709108689927582\n",
      "  5%: -1.9416363771666616\n",
      "  10%: -1.6162221170422162\n",
      "\n",
      "\n",
      "Resultados del test ADF para unempoyment:\n",
      "  ADF Statistic: -15.074402716025384\n",
      "  p-value: 9.666746129473828e-27\n",
      "  1%: -2.5708870614847235\n",
      "  5%: -1.94163337991128\n",
      "  10%: -1.6162247966589938\n",
      "\n",
      "\n",
      "Resultados del test ADF para cons_sent:\n",
      "  ADF Statistic: -9.81927040645136\n",
      "  p-value: 2.5000794955285112e-17\n",
      "  1%: -2.570946996086369\n",
      "  5%: -1.9416409265499461\n",
      "  10%: -1.6162180520712746\n",
      "\n",
      "\n",
      "Resultados del test ADF para m2:\n",
      "  ADF Statistic: -2.2894583171875507\n",
      "  p-value: 0.021221006207111776\n",
      "  1%: -2.5709836315398724\n",
      "  5%: -1.94164554136314\n",
      "  10%: -1.6162139314477124\n",
      "\n",
      "\n",
      "Resultados del test ADF para fed_funds:\n",
      "  ADF Statistic: -7.326885630586593\n",
      "  p-value: 1.1133543648616222e-11\n",
      "  1%: -2.5709228555275243\n",
      "  5%: -1.9416378864437647\n",
      "  10%: -1.6162207681657739\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Se realiza el test ADF para cada variable sin constante ni tendencia\n",
    "adf_results_diff_nc = {}\n",
    "for column in diff_data.columns[1:]:\n",
    "    adf_test_diff_nc = adfuller(diff_data[column], regression='n', autolag='AIC')\n",
    "    adf_results_diff_nc[column] = {\n",
    "        'ADF Statistic': adf_test_diff_nc[0],\n",
    "        'p-value': adf_test_diff_nc[1],\n",
    "        'Critical Values': adf_test_diff_nc[4]\n",
    "\n",
    "    }\n",
    "\n",
    "print(\"Resultados del test ADF sin constante ni tendencia (diferencias):\")\n",
    "for column, result in adf_results_diff_nc.items():\n",
    "    print(f\"Resultados del test ADF para {column}:\")\n",
    "    print(f\"  ADF Statistic: {result['ADF Statistic']}\")\n",
    "    print(f\"  p-value: {result['p-value']}\")\n",
    "    for key, value in result['Critical Values'].items():\n",
    "        print(f\"  {key}: {value}\")\n",
    "    print(\"\\n\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "En ambos test ADF (Tanto el que incorpora la constante y tendencia como el que no), todas las variables son estacionarias. Es decir, son integradas de orden 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Se debe excluir a la variable de fecha para hacer la matriz de correlación\n",
    "sacar = ['DATE'] \n",
    "diff_data_filtrado = diff_data.drop(columns=sacar)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Calcular la matriz de correlación\n",
    "correlograma_incisob = diff_data_filtrado.corr()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 69776 characters]",
      "text/plain": [
       "<Figure size 1000x800 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Mostrar el correlograma\n",
    "plt.figure(figsize=(10, 8))\n",
    "sns.heatmap(correlograma_incisob, annot=True, cmap='RdBu_r', vmin=-1, vmax=1, center=0, cbar=True)\n",
    "\n",
    "plt.title('Matriz de Correlación (Diferencias)', fontsize=16)\n",
    "plt.xticks(rotation=45)\n",
    "plt.yticks(rotation=0)\n",
    "plt.tight_layout()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "La inflación es la tasa de crecimiento de los precios. Dado que se aplicó transformación logarítmica a todo el dataset y luego se obtuvo la priumera diferencia, entonces todo el data set que se maneja ahora es la tasa de crecimiento de las variables. \n",
    "Por lo tanto, la variable de los precios en el dataframe actual es la tasa de crecimiento de los precios, es decir, la inflación."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Se toma en cuenta a la variable cpi como la inflación\n",
    "\n",
    "# Se separa la variable objetivo (tasa de inflación) y los predictores\n",
    "\n",
    "var_objetivo = 'cpi' \n",
    "X = diff_data_filtrado.drop(columns=[var_objetivo])  # Matriz de predictores\n",
    "y = diff_data_filtrado[var_objetivo]  # Vector de la variable objetivo\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Escalar los predictores usando StandardScaler\n",
    "scaler = StandardScaler()\n",
    "X_escalada = scaler.fit_transform(X)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Se convierte x_escalada nuevamente a un DataFrame para conservar los nombres de las columnas\n",
    "X_escalada = pd.DataFrame(X_escalada, columns=X.columns, index=X.index)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Media de las variables:\n",
      "wti           -8.111218e-18\n",
      "unempoyment    5.069512e-19\n",
      "cons_sent      1.115293e-17\n",
      "m2            -6.488975e-17\n",
      "fed_funds      3.092402e-17\n",
      "dtype: float64\n",
      "\n",
      "Desviación estándar de las variables:\n",
      "wti            1.001144\n",
      "unempoyment    1.001144\n",
      "cons_sent      1.001144\n",
      "m2             1.001144\n",
      "fed_funds      1.001144\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# Para verificar que las variables estés escaladas, se calcula la media y desviación estándar de cada columna en X_escalada\n",
    "promedio_incisoc = X_escalada.mean()\n",
    "sd_incisoc = X_escalada.std()\n",
    "\n",
    "print(\"Media de las variables:\")\n",
    "print(promedio_incisoc)\n",
    "\n",
    "print(\"\\nDesviación estándar de las variables:\")\n",
    "print(sd_incisoc)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Las variables fueron escaladas y ahora presentan media 0 y desviación estándar de 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tamaños de los conjuntos:\n",
      "Entrenamiento: X_train=(350, 5), y_train=(350,)\n",
      "Validación: X_validation=(44, 5), y_validation=(44,)\n",
      "Testeo: X_test=(44, 5), y_test=(44,)\n"
     ]
    }
   ],
   "source": [
    "train_tam = 0.8\n",
    "validacion_tam = 0.1\n",
    "\n",
    "# Se calculan los índices para las divisiones\n",
    "n = len(X_escalada) \n",
    "train_fin = int(n * train_tam)\n",
    "validacion_fin = int(n * (train_tam + validacion_tam))\n",
    "\n",
    "# Se divide la matriz de predictores y el vector dela variable objetivo\n",
    "X_train = X_escalada.iloc[:train_fin]\n",
    "y_train = y.iloc[:train_fin]\n",
    "\n",
    "X_validation = X_escalada.iloc[train_fin:validacion_fin]\n",
    "y_validation = y.iloc[train_fin:validacion_fin]\n",
    "\n",
    "X_test = X_escalada.iloc[validacion_fin:]\n",
    "y_test = y.iloc[validacion_fin:]\n",
    "\n",
    "# Se verifica el tanaño de los conjuntos\n",
    "print(\"Tamaños de los conjuntos:\")\n",
    "print(f\"Entrenamiento: X_train={X_train.shape}, y_train={y_train.shape}\")\n",
    "print(f\"Validación: X_validation={X_validation.shape}, y_validation={y_validation.shape}\")\n",
    "print(f\"Testeo: X_test={X_test.shape}, y_test={y_test.shape}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Importación de librerías para el árbol de decisión y error cuadrático medio\n",
    "from sklearn.tree import DecisionTreeRegressor, plot_tree\n",
    "from sklearn.metrics import mean_squared_error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: #000;\n",
       "  --sklearn-color-text-muted: #666;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-1 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-1 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: flex;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "  align-items: start;\n",
       "  justify-content: space-between;\n",
       "  gap: 0.5em;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label .caption {\n",
       "  font-size: 0.6rem;\n",
       "  font-weight: lighter;\n",
       "  color: var(--sklearn-color-text-muted);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-1 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-1 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-1 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 0.5em;\n",
       "  text-align: center;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-1 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>DecisionTreeRegressor(max_depth=7, random_state=42)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow\"><div><div>DecisionTreeRegressor</div></div><div><a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.6/modules/generated/sklearn.tree.DecisionTreeRegressor.html\">?<span>Documentation for DecisionTreeRegressor</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></div></label><div class=\"sk-toggleable__content fitted\"><pre>DecisionTreeRegressor(max_depth=7, random_state=42)</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "DecisionTreeRegressor(max_depth=7, random_state=42)"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Crear y entrenar el modelo de árbol de decisión con profundidad máxima de 7\n",
    "model = DecisionTreeRegressor(max_depth=7, random_state=42)\n",
    "model.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 449292 characters]",
      "text/plain": [
       "<Figure size 2000x1000 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Gráfico el árbol entrenado\n",
    "plt.figure(figsize=(20, 10))\n",
    "plot_tree(model, feature_names=X_train.columns.tolist(), filled=True, fontsize=10)\n",
    "plt.title(\"Árbol de Decisión Entrenado\", fontsize=16)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.00619235,  0.00495965,  0.00495965,  0.00172879, -0.00152379,\n",
       "        0.00172879,  0.00222089,  0.00367412, -0.00152379,  0.00172879,\n",
       "        0.00495965,  0.00105632, -0.00137562,  0.00109173,  0.00495965,\n",
       "        0.00495965,  0.00062529,  0.00495965,  0.0121459 , -0.00137562,\n",
       "       -0.00543614, -0.00137562,  0.00367412,  0.0032688 , -0.00137562,\n",
       "        0.00367412,  0.00213616,  0.0032688 ,  0.00222089, -0.00399955,\n",
       "       -0.00176275,  0.00222089,  0.00708699,  0.00495965,  0.0032688 ,\n",
       "       -0.00137562, -0.00543614,  0.00172879,  0.00172879,  0.00172879,\n",
       "        0.00172879,  0.0032688 ,  0.00172879,  0.00172879])"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Obtener las predicciones del modelo en el conjunto de testeo\n",
    "y_pred = model.predict(X_test)\n",
    "y_pred\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Raíz del Error Cuadrático Medio (RMSE) en el conjunto de testeo: 0.0042\n"
     ]
    }
   ],
   "source": [
    "# Calcular la raíz del error cuadrático medio (RMSE) en el conjunto de testeo\n",
    "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n",
    "print(f\"Raíz del Error Cuadrático Medio (RMSE) en el conjunto de testeo: {rmse:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Lista para almacenar los errores del conjunto de validación\n",
    "errores_validacion = []\n",
    "ccp_alphas = model.cost_complexity_pruning_path(X_train, y_train).ccp_alphas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Entrenar múltiples árboles con diferentes valores de ccp_alpha\n",
    "for ccp_alpha in ccp_alphas:\n",
    "    temp_model = DecisionTreeRegressor(random_state=42, ccp_alpha=ccp_alpha)\n",
    "    temp_model.fit(X_train, y_train)\n",
    "    y_validation_pred = temp_model.predict(X_validation)\n",
    "    validation_error = mean_squared_error(y_validation, y_validation_pred)\n",
    "    errores_validacion.append(validation_error)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Encontrar el ccp_alpha con el menor error en el conjunto de validación\n",
    "optimal_alpha = ccp_alphas[np.argmin(errores_validacion)]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-2 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: #000;\n",
       "  --sklearn-color-text-muted: #666;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-2 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-2 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-2 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: flex;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "  align-items: start;\n",
       "  justify-content: space-between;\n",
       "  gap: 0.5em;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 label.sk-toggleable__label .caption {\n",
       "  font-size: 0.6rem;\n",
       "  font-weight: lighter;\n",
       "  color: var(--sklearn-color-text-muted);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-2 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-2 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-2 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-2 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-2 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 0.5em;\n",
       "  text-align: center;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-2 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>DecisionTreeRegressor(ccp_alpha=np.float64(3.0759871187020693e-07),\n",
       "                      random_state=42)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" checked><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow\"><div><div>DecisionTreeRegressor</div></div><div><a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.6/modules/generated/sklearn.tree.DecisionTreeRegressor.html\">?<span>Documentation for DecisionTreeRegressor</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></div></label><div class=\"sk-toggleable__content fitted\"><pre>DecisionTreeRegressor(ccp_alpha=np.float64(3.0759871187020693e-07),\n",
       "                      random_state=42)</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "DecisionTreeRegressor(ccp_alpha=np.float64(3.0759871187020693e-07),\n",
       "                      random_state=42)"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Entrenar el árbol con el ccp_alpha óptimo\n",
    "optimal_model = DecisionTreeRegressor(random_state=42, ccp_alpha=optimal_alpha)\n",
    "optimal_model.fit(X_train, y_train)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 113788 characters]",
      "text/plain": [
       "<Figure size 2000x1000 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.figure(figsize=(20, 10))\n",
    "plot_tree(optimal_model, feature_names=X_train.columns.tolist(), filled=True, fontsize=10)\n",
    "plt.title(\"Subárbol Óptimo\", fontsize=16)\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.00301078,  0.00301078,  0.00301078,  0.00301078,  0.00157798,\n",
       "        0.00301078,  0.00301078,  0.00301078,  0.00157798,  0.00301078,\n",
       "        0.00301078,  0.00157798, -0.00042005,  0.00301078,  0.00301078,\n",
       "        0.00301078,  0.00157798,  0.00301078,  0.0103367 , -0.00042005,\n",
       "        0.00157798, -0.00042005,  0.00301078,  0.00157798, -0.00042005,\n",
       "        0.00301078,  0.00157798,  0.00157798,  0.00301078, -0.00042005,\n",
       "        0.00157798,  0.00301078,  0.00301078,  0.00301078,  0.00157798,\n",
       "       -0.00042005,  0.00157798,  0.00301078,  0.00301078,  0.00301078,\n",
       "        0.00301078,  0.00157798,  0.00301078,  0.00301078])"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Obtener las predicciones del subárbol óptimo en el conjunto de testeo\n",
    "y_test_pred = optimal_model.predict(X_test)\n",
    "y_test_pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Raíz del Error Cuadrático Medio (RMSE) en el conjunto de testeo: 0.0037\n"
     ]
    }
   ],
   "source": [
    "# Calcular la raíz del error cuadrático medio (RMSE) en el conjunto de testeo\n",
    "optimal_rmse = np.sqrt(mean_squared_error(y_test, y_test_pred))\n",
    "print(f\"Raíz del Error Cuadrático Medio (RMSE) en el conjunto de testeo: {optimal_rmse:.4f}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Importar librerías para Random Forest y GridSearchCV\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.metrics import mean_squared_error\n",
    "from sklearn.model_selection import GridSearchCV\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Definir el grid de hiperparámetros\n",
    "param_grid = {\n",
    "    'n_estimators': [50, 100, 250, 500, 1000],\n",
    "    'max_features': [2, 3, 4]\n",
    "}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Crear el modelo de Random Forest\n",
    "rf_model = RandomForestRegressor(random_state=42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fitting 3 folds for each of 15 candidates, totalling 45 fits\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-3 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: #000;\n",
       "  --sklearn-color-text-muted: #666;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-3 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-3 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-3 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-3 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-3 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: flex;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "  align-items: start;\n",
       "  justify-content: space-between;\n",
       "  gap: 0.5em;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 label.sk-toggleable__label .caption {\n",
       "  font-size: 0.6rem;\n",
       "  font-weight: lighter;\n",
       "  color: var(--sklearn-color-text-muted);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-3 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-3 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-3 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-3 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-3 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-3 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-3 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-3 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-3 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-3 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 0.5em;\n",
       "  text-align: center;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-3 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-3 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-3 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-3\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=3, estimator=RandomForestRegressor(random_state=42), n_jobs=-1,\n",
       "             param_grid={&#x27;max_features&#x27;: [2, 3, 4],\n",
       "                         &#x27;n_estimators&#x27;: [50, 100, 250, 500, 1000]},\n",
       "             scoring=&#x27;neg_mean_squared_error&#x27;, verbose=1)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-3\" type=\"checkbox\" ><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow\"><div><div>GridSearchCV</div></div><div><a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.6/modules/generated/sklearn.model_selection.GridSearchCV.html\">?<span>Documentation for GridSearchCV</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></div></label><div class=\"sk-toggleable__content fitted\"><pre>GridSearchCV(cv=3, estimator=RandomForestRegressor(random_state=42), n_jobs=-1,\n",
       "             param_grid={&#x27;max_features&#x27;: [2, 3, 4],\n",
       "                         &#x27;n_estimators&#x27;: [50, 100, 250, 500, 1000]},\n",
       "             scoring=&#x27;neg_mean_squared_error&#x27;, verbose=1)</pre></div> </div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow\"><div><div>best_estimator_: RandomForestRegressor</div></div></label><div class=\"sk-toggleable__content fitted\"><pre>RandomForestRegressor(max_features=2, n_estimators=1000, random_state=42)</pre></div> </div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" ><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow\"><div><div>RandomForestRegressor</div></div><div><a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.6/modules/generated/sklearn.ensemble.RandomForestRegressor.html\">?<span>Documentation for RandomForestRegressor</span></a></div></label><div class=\"sk-toggleable__content fitted\"><pre>RandomForestRegressor(max_features=2, n_estimators=1000, random_state=42)</pre></div> </div></div></div></div></div></div></div></div></div>"
      ],
      "text/plain": [
       "GridSearchCV(cv=3, estimator=RandomForestRegressor(random_state=42), n_jobs=-1,\n",
       "             param_grid={'max_features': [2, 3, 4],\n",
       "                         'n_estimators': [50, 100, 250, 500, 1000]},\n",
       "             scoring='neg_mean_squared_error', verbose=1)"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Configurar el GridSearchCV para encontrar los mejores hiperparámetros\n",
    "grid_search = GridSearchCV(\n",
    "    estimator=rf_model,\n",
    "    param_grid=param_grid,\n",
    "    scoring='neg_mean_squared_error',  # Maximizar el negativo del error cuadrático medio\n",
    "    cv=3,  # Validación cruzada con 3 particiones\n",
    "    verbose=1,\n",
    "    n_jobs=-1  # Utilizar todos los núcleos disponibles\n",
    ")\n",
    "\n",
    "# Ajustar el modelo al conjunto de entrenamiento\n",
    "grid_search.fit(X_train, y_train)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mejores hiperparámetros encontrados: {'max_features': 2, 'n_estimators': 1000}\n",
      "Raíz del Error Cuadrático Medio (RMSE) en el conjunto de validación: 0.0032\n"
     ]
    }
   ],
   "source": [
    "# Obtener los mejores hiperparámetros y el mejor modelo\n",
    "best_params = grid_search.best_params_\n",
    "best_rf_model = grid_search.best_estimator_\n",
    "\n",
    "# Calcular el error cuadrático medio en el conjunto de validación\n",
    "best_validation_rmse = np.sqrt(-grid_search.best_score_)\n",
    "\n",
    "print(\"Mejores hiperparámetros encontrados:\", best_params)\n",
    "print(f\"Raíz del Error Cuadrático Medio (RMSE) en el conjunto de validación: {best_validation_rmse:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Raíz del Error Cuadrático Medio (RMSE) del modelo Random Forest en el conjunto de testeo: 0.0038\n"
     ]
    }
   ],
   "source": [
    "# Obtener las predicciones del modelo Random Forest óptimo sobre el conjunto de testeo\n",
    "y_test_pred_rf = best_rf_model.predict(X_test)\n",
    "\n",
    "# Calcular la raíz del error cuadrático medio (RMSE) en el conjunto de testeo\n",
    "rf_rmse = np.sqrt(mean_squared_error(y_test, y_test_pred_rf))\n",
    "\n",
    "# Imprimir los resultados\n",
    "print(f\"Raíz del Error Cuadrático Medio (RMSE) del modelo Random Forest en el conjunto de testeo: {rf_rmse:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Comparación con modelos previos:\n",
      "- RMSE del árbol de decisión original: 0.0042\n",
      "- RMSE del subárbol óptimo: 0.0037\n",
      "- RMSE del modelo Random Forest: 0.0038\n"
     ]
    }
   ],
   "source": [
    "# Comparar con los resultados de modelos previos\n",
    "print(\"\\nComparación con modelos previos:\")\n",
    "print(f\"- RMSE del árbol de decisión original: {rmse:.4f}\")\n",
    "print(f\"- RMSE del subárbol óptimo: {optimal_rmse:.4f}\")\n",
    "print(f\"- RMSE del modelo Random Forest: {rf_rmse:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ponderación óptima (Random Forest): 0.2857\n",
      "RMSE mínimo de la combinación: 0.0036\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 114332 characters]",
      "text/plain": [
       "<Figure size 1200x600 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Generar un grid de 50 ponderaciones entre 0 y 1\n",
    "weights = np.linspace(0, 1, 50)\n",
    "\n",
    "# Lista para almacenar los errores\n",
    "rmse_combined = []\n",
    "\n",
    "# Calcular las predicciones combinadas y su RMSE\n",
    "for w in weights:\n",
    "    combined_pred = w * y_test_pred_rf + (1 - w) * y_test_pred\n",
    "    rmse = np.sqrt(mean_squared_error(y_test, combined_pred))\n",
    "    rmse_combined.append(rmse)\n",
    "\n",
    "# Encontrar la ponderación óptima\n",
    "optimal_weight = weights[np.argmin(rmse_combined)]\n",
    "optimal_rmse = min(rmse_combined)\n",
    "\n",
    "# Predicciones combinadas óptimas\n",
    "optimal_combined_pred = optimal_weight * y_test_pred_rf + (1 - optimal_weight) * y_test_pred\n",
    "\n",
    "# Imprimir resultados\n",
    "print(f\"Ponderación óptima (Random Forest): {optimal_weight:.4f}\")\n",
    "print(f\"RMSE mínimo de la combinación: {optimal_rmse:.4f}\")\n",
    "\n",
    "# Graficar las predicciones combinadas y la tasa de inflación real (CPI)\n",
    "plt.figure(figsize=(12, 6))\n",
    "plt.plot(y_test.values, label=\"Tasa de inflación real (CPI)\", color='blue', linewidth=2)\n",
    "plt.plot(optimal_combined_pred, label=\"Predicción combinada\", color='orange', linestyle='--', linewidth=2)\n",
    "plt.title(\"Predicciones Combinadas vs Tasa de Inflación (CPI)\", fontsize=16)\n",
    "plt.xlabel(\"Índice de Tiempo\", fontsize=12)\n",
    "plt.ylabel(\"Tasa de Inflación (CPI)\", fontsize=12)\n",
    "plt.legend(fontsize=12)\n",
    "plt.grid()\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Segunda parte: Calificación Crediticia y Predicción de Riesgo"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Objetivo: Determinar la probabilidad de deterioro crediticio en empresas o emisiones, para una gestión más efectiva del riesgo."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Modelos aplicados:\n",
    "Regresión Logística (Logit) para estimar la probabilidad de default o de pertenecer a ciertas categorías de calificación.\n",
    "Análisis Discriminante Lineal para segmentar y clasificar con base en un conjunto de indicadores financieros (apalancamiento, liquidez, rentabilidad, etc.)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Resultados:\n",
    "El modelo logístico alcanzó una exactitud superior al 85%, demostrando su utilidad para la toma de decisiones en la asignación de ratings.\n",
    "El discriminante lineal ofreció una tasa de acierto de alrededor del 80%, confirmando su validez como método más sencillo y explicable, especialmente útil en contextos regulados."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Rating  ID   Income  Limit  Cards  Age  Education  Balance  Gender_Female  \\\n",
      "0       0   1   14.891   3606      2   34         11      333          False   \n",
      "1       1   2  106.025   6645      3   82         15      903           True   \n",
      "2       1   3  104.593   7075      4   71         11      580          False   \n",
      "3       1   4  148.924   9504      3   36         11      964           True   \n",
      "4       1   5   55.882   4897      2   68         16      331          False   \n",
      "\n",
      "   Student_Yes  Married_Yes  Ethnicity_Asian  Ethnicity_Caucasian  \n",
      "0        False         True            False                 True  \n",
      "1         True         True             True                False  \n",
      "2        False        False             True                False  \n",
      "3        False        False             True                False  \n",
      "4        False         True            False                 True  \n"
     ]
    }
   ],
   "source": [
    "# Lee los archivos CSV en Pandas DataFrames\n",
    "credit_rating = pd.read_csv('credit_rating.csv')\n",
    "credit_regressors = pd.read_csv('credit_regressors.csv')\n",
    "\n",
    "# Realizar el merge usando la primera columna como clave\n",
    "merged_data = pd.merge(credit_rating, credit_regressors, left_on=credit_rating.columns[0], right_on=credit_regressors.columns[0])\n",
    "\n",
    "# Eliminar la columna duplicada que resulta del merge\n",
    "merged_data = merged_data.drop(columns=[merged_data.columns[0]])\n",
    "\n",
    "# Identificar las columnas categóricas\n",
    "categorical_columns = merged_data.select_dtypes(include=['object', 'category']).columns\n",
    "\n",
    "# Realizar el encoding de las variables categóricas\n",
    "merged_data_encoded = pd.get_dummies(merged_data, columns=categorical_columns, drop_first=True)\n",
    "\n",
    "# Mostrar las primeras filas del dataset transformado\n",
    "print(merged_data_encoded.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "X_train dimensiones: (300, 12)\n",
      "X_test dimensiones: (100, 12)\n",
      "y_train dimensiones: (300,)\n",
      "y_test dimensiones: (100,)\n"
     ]
    }
   ],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "\n",
    "# Dividir los datos en predictores (X) y variable objetivo (y)\n",
    "X = merged_data_encoded.drop(columns=[\"Rating\"])  # \"Rating\" es la variable objetivo\n",
    "y = merged_data_encoded[\"Rating\"]\n",
    "\n",
    "\n",
    "# Divide los datos en conjuntos de entrenamiento y prueba\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n",
    "\n",
    "# Muestra las dimensiones de los conjuntos de datos\n",
    "print(\"X_train dimensiones:\", X_train.shape)\n",
    "print(\"X_test dimensiones:\", X_test.shape)\n",
    "print(\"y_train dimensiones:\", y_train.shape)\n",
    "print(\"y_test dimensiones:\", y_test.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matriz de Confusión:\n",
      " [[44  1]\n",
      " [ 7 48]]\n",
      "Precisión: 0.92\n",
      "Sensibilidad: 0.8727272727272727\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\NICO\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\sklearn\\linear_model\\_logistic.py:465: ConvergenceWarning: lbfgs failed to converge (status=1):\n",
      "STOP: TOTAL NO. OF ITERATIONS REACHED LIMIT.\n",
      "\n",
      "Increase the number of iterations (max_iter) or scale the data as shown in:\n",
      "    https://scikit-learn.org/stable/modules/preprocessing.html\n",
      "Please also refer to the documentation for alternative solver options:\n",
      "    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n",
      "  n_iter_i = _check_optimize_result(\n"
     ]
    }
   ],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.metrics import confusion_matrix, accuracy_score, recall_score\n",
    "\n",
    "# Ajusta el modelo de regresión logística\n",
    "model = LogisticRegression(max_iter=1000)\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "# Predice en el conjunto de prueba\n",
    "y_pred = model.predict(X_test)\n",
    "\n",
    "# Calcula la matriz de confusión\n",
    "cm = confusion_matrix(y_test, y_pred)\n",
    "\n",
    "# Calcula la precisión\n",
    "accuracy = accuracy_score(y_test, y_pred)\n",
    "\n",
    "# Calcula la sensibilidad\n",
    "recall = recall_score(y_test, y_pred)\n",
    "\n",
    "# Imprime la matriz de confusión, la precisión y la sensibilidad\n",
    "print(\"Matriz de Confusión:\\n\", cm)\n",
    "print(\"Precisión:\", accuracy)\n",
    "print(\"Sensibilidad:\", recall)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matriz de Confusión LDA:\n",
      " [[40  5]\n",
      " [ 9 46]]\n",
      "Precisión LDA: 0.86\n",
      "Sensibilidad LDA: 0.8363636363636363\n"
     ]
    }
   ],
   "source": [
    "from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n",
    "from sklearn.metrics import confusion_matrix, accuracy_score, recall_score\n",
    "\n",
    "# Inicializa el modelo LDA\n",
    "lda = LinearDiscriminantAnalysis()\n",
    "\n",
    "# Ajusta el modelo a los datos de entrenamiento\n",
    "lda.fit(X_train, y_train)\n",
    "\n",
    "# Predice en el conjunto de prueba\n",
    "y_pred_lda = lda.predict(X_test)\n",
    "\n",
    "# Calcula la matriz de confusión\n",
    "cm_lda = confusion_matrix(y_test, y_pred_lda)\n",
    "\n",
    "# Calcula la precisión\n",
    "accuracy_lda = accuracy_score(y_test, y_pred_lda)\n",
    "\n",
    "# Calcula la sensibilidad\n",
    "recall_lda = recall_score(y_test, y_pred_lda)\n",
    "\n",
    "# Imprime la matriz de confusión, la precisión y la sensibilidad\n",
    "print(\"Matriz de Confusión LDA:\\n\", cm_lda)\n",
    "print(\"Precisión LDA:\", accuracy_lda)\n",
    "print(\"Sensibilidad LDA:\", recall_lda)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Tercera parte: Gestión de Riesgo de Mercado: VaR, Montecarlo y Modelos de Cambio de Régimen"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Contexto: Se tomó como referencia el ETF SPY, un activo basado en el S&P 500, integrando la tasa de la Fed en el análisis para capturar posibles efectos en la renta variable."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Técnicas empleadas:\n",
    "Estimación del Value at Risk (VaR) mediante enfoques paramétricos y por simulación, a niveles de confianza del 95% y 99%.\n",
    "Simulación de Montecarlo para evaluar pérdidas extremas y escenarios de alta volatilidad.\n",
    "Modelos Markov Switching (MS-DR y MS-AR) para capturar cambios abruptos en el régimen de volatilidad de la tasa de la Fed y su impacto en los rendimientos del SPY.\n",
    "Regresiones Cuántiles, que permiten estudiar el efecto de las variaciones de la tasa en diferentes percentiles de rendimiento."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Beneficios obtenidos:\n",
    "El VaR resultó congruente con las pérdidas reales en escenarios de estrés, validando la utilidad de estas estimaciones para la gestión de portafolios.\n",
    "Los modelos de cambio de régimen detectaron periodos de alta volatilidad, facilitando la adopción de estrategias oportunas de cobertura.\n",
    "El análisis cuantil confirmó que los aumentos en la tasa de la Fed tienen un efecto negativo más pronunciado en los peores rendimientos del SPY, vital para estrategias de stress testing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[*********************100%***********************]  1 of 1 completed\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>Ticker</th>\n",
       "      <th>SPY</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2010-01-04</th>\n",
       "      <td>86.026459</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-05</th>\n",
       "      <td>86.254173</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-06</th>\n",
       "      <td>86.314896</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-07</th>\n",
       "      <td>86.679260</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-08</th>\n",
       "      <td>86.967712</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-23</th>\n",
       "      <td>450.377136</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-27</th>\n",
       "      <td>456.750946</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-28</th>\n",
       "      <td>456.377686</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-29</th>\n",
       "      <td>456.961548</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-30</th>\n",
       "      <td>455.698242</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3020 rows × 1 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "Ticker             SPY\n",
       "Date                  \n",
       "2010-01-04   86.026459\n",
       "2010-01-05   86.254173\n",
       "2010-01-06   86.314896\n",
       "2010-01-07   86.679260\n",
       "2010-01-08   86.967712\n",
       "...                ...\n",
       "2021-12-23  450.377136\n",
       "2021-12-27  456.750946\n",
       "2021-12-28  456.377686\n",
       "2021-12-29  456.961548\n",
       "2021-12-30  455.698242\n",
       "\n",
       "[3020 rows x 1 columns]"
      ]
     },
     "execution_count": 173,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import yfinance as yf\n",
    "import datetime\n",
    "from datetime import datetime\n",
    "\n",
    "ticker=['SPY']\n",
    "start= datetime(2009,12,31)\n",
    "end= datetime(2021,12,31)\n",
    "sp500= yf.download(ticker, start, end)['Close']\n",
    "sp500"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 174,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>Ticker</th>\n",
       "      <th>SPY</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2010-01-05</th>\n",
       "      <td>0.002647</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-06</th>\n",
       "      <td>0.000704</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-07</th>\n",
       "      <td>0.004221</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-08</th>\n",
       "      <td>0.003328</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-11</th>\n",
       "      <td>0.001397</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-23</th>\n",
       "      <td>0.006222</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-27</th>\n",
       "      <td>0.014152</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-28</th>\n",
       "      <td>-0.000817</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-29</th>\n",
       "      <td>0.001279</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-30</th>\n",
       "      <td>-0.002765</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3019 rows × 1 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "Ticker           SPY\n",
       "Date                \n",
       "2010-01-05  0.002647\n",
       "2010-01-06  0.000704\n",
       "2010-01-07  0.004221\n",
       "2010-01-08  0.003328\n",
       "2010-01-11  0.001397\n",
       "...              ...\n",
       "2021-12-23  0.006222\n",
       "2021-12-27  0.014152\n",
       "2021-12-28 -0.000817\n",
       "2021-12-29  0.001279\n",
       "2021-12-30 -0.002765\n",
       "\n",
       "[3019 rows x 1 columns]"
      ]
     },
     "execution_count": 174,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rate_sp500= sp500.pct_change().dropna()\n",
    "rate_sp500"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 175,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "np.float64(-0.01616725699746453)"
      ]
     },
     "execution_count": 175,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Calcular el VaR al 5% usando el método histórico\n",
    "var95=np.percentile(rate_sp500['SPY'], 5)\n",
    "var95"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "En el 5% de los peores escenarios se pierde 1.62%"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 176,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>Ticker</th>\n",
       "      <th>SPY</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2010-01-05</th>\n",
       "      <td>0.002647</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-06</th>\n",
       "      <td>0.000704</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-07</th>\n",
       "      <td>0.004221</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-08</th>\n",
       "      <td>0.003328</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-11</th>\n",
       "      <td>0.001397</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-23</th>\n",
       "      <td>0.006222</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-27</th>\n",
       "      <td>0.014152</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-28</th>\n",
       "      <td>-0.000817</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-29</th>\n",
       "      <td>0.001279</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-30</th>\n",
       "      <td>-0.002765</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3019 rows × 1 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "Ticker           SPY\n",
       "Date                \n",
       "2010-01-05  0.002647\n",
       "2010-01-06  0.000704\n",
       "2010-01-07  0.004221\n",
       "2010-01-08  0.003328\n",
       "2010-01-11  0.001397\n",
       "...              ...\n",
       "2021-12-23  0.006222\n",
       "2021-12-27  0.014152\n",
       "2021-12-28 -0.000817\n",
       "2021-12-29  0.001279\n",
       "2021-12-30 -0.002765\n",
       "\n",
       "[3019 rows x 1 columns]"
      ]
     },
     "execution_count": 176,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rate_sp500"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 181,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Calcular la media y la desviación estándar de los retornos diarios\n",
    "mu = rate_sp500['SPY'].mean()\n",
    "sigma = rate_sp500['SPY'].std()\n",
    "\n",
    "#  Generar simulaciones de Monte Carlo para los retornos diarios\n",
    "n_simulations = 1000  # Número de simulaciones\n",
    "n_days = 252  # Número de días de negociación en un año\n",
    "simulated_returns = np.random.normal(mu, sigma, (n_simulations, n_days))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 182,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "El VaR(5%) estimado es: -15.32%\n"
     ]
    }
   ],
   "source": [
    "# Calcular los retornos acumulados para cada simulación\n",
    "cumulative_returns = (1 + simulated_returns).cumprod(axis=1)\n",
    "\n",
    "# Calcular el VaR(5%)\n",
    "var_5 = np.percentile(cumulative_returns[:, -1] - 1, 5)\n",
    "\n",
    "print(f\"El VaR(5%) estimado es: {var_5:.2%}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 183,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 654364 characters]",
      "text/plain": [
       "<Figure size 1000x600 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "# Crear la gráfica\n",
    "plt.figure(figsize=(10, 6))  # Ajustar el tamaño de la figura\n",
    "plt.plot(cumulative_returns.T, alpha=0.5)  # Graficar todas las simulaciones con transparencia\n",
    "plt.plot(cumulative_returns.mean(axis=0), color='black', linewidth=3, label='Average')  # Graficar la media\n",
    "plt.xlabel('Year')  # Etiqueta del eje x\n",
    "plt.grid(True)  # Agregar cuadrícula\n",
    "plt.legend()  # Mostrar leyenda\n",
    "plt.title('Monte Carlo Simulation of Cumulative Returns')  # Agregar título\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 229,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 31748 characters]",
      "text/plain": [
       "<Figure size 1000x500 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>FED</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2010-01-01</th>\n",
       "      <td>0.11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-02-01</th>\n",
       "      <td>0.13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-03-01</th>\n",
       "      <td>0.16</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-04-01</th>\n",
       "      <td>0.20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-05-01</th>\n",
       "      <td>0.20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-08-01</th>\n",
       "      <td>5.33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-01</th>\n",
       "      <td>5.13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-10-01</th>\n",
       "      <td>4.83</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-11-01</th>\n",
       "      <td>4.64</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-12-01</th>\n",
       "      <td>4.48</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>180 rows × 1 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "             FED\n",
       "Date            \n",
       "2010-01-01  0.11\n",
       "2010-02-01  0.13\n",
       "2010-03-01  0.16\n",
       "2010-04-01  0.20\n",
       "2010-05-01  0.20\n",
       "...          ...\n",
       "2024-08-01  5.33\n",
       "2024-09-01  5.13\n",
       "2024-10-01  4.83\n",
       "2024-11-01  4.64\n",
       "2024-12-01  4.48\n",
       "\n",
       "[180 rows x 1 columns]"
      ]
     },
     "execution_count": 229,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import statsmodels.api as sm\n",
    "from statsmodels.tsa.regime_switching.markov_regression import MarkovRegression\n",
    "\n",
    "# Cargar los datos de tasas de Federal Funds\n",
    "df_fed = pd.read_csv(\"fed_funds_rate_2010_2024.csv\", parse_dates=[\"Date\"], index_col=\"Date\")\n",
    "\n",
    "# Renombrar la columna de tasas\n",
    "df_fed.rename(columns={\"Fed Funds Rate\": \"FED\"}, inplace=True)\n",
    "\n",
    "# Asegurar que los datos estén ordenados por fecha\n",
    "df_fed.sort_index(inplace=True)\n",
    "\n",
    "# Graficar los retornos\n",
    "plt.figure(figsize=(10,5))\n",
    "plt.plot(df_fed.index, df_fed[\"FED\"], label=\"FED\", color=\"blue\")\n",
    "plt.axhline(0, color='black', linewidth=0.8, linestyle='--')\n",
    "plt.title(\"Retornos de la tasa de Federal Funds\")\n",
    "plt.xlabel(\"Fecha\")\n",
    "plt.ylabel(\"Retorno\")\n",
    "plt.legend()\n",
    "plt.show()\n",
    "df_fed\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "MS-AR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 206,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\NICO\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\statsmodels\\tsa\\base\\tsa_model.py:473: ValueWarning: No frequency information was provided, so inferred frequency MS will be used.\n",
      "  self._init_dates(dates, freq)\n",
      "C:\\Users\\NICO\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\statsmodels\\base\\model.py:607: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals\n",
      "  warnings.warn(\"Maximum Likelihood optimization failed to \"\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                         Markov Switching Model Results                         \n",
      "================================================================================\n",
      "Dep. Variable:                      FED   No. Observations:                  176\n",
      "Model:             MarkovAutoregression   Log Likelihood                 177.422\n",
      "Date:                  Fri, 31 Jan 2025   AIC                           -312.844\n",
      "Time:                          01:51:49   BIC                           -246.263\n",
      "Sample:                      01-01-2010   HQIC                          -285.839\n",
      "                           - 12-01-2024                                         \n",
      "Covariance Type:                 approx                                         \n",
      "                             Regime 0 parameters                              \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const          1.7383      0.993      1.750      0.080      -0.208       3.685\n",
      "                             Regime 1 parameters                              \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const          1.7329      0.993      1.744      0.081      -0.214       3.680\n",
      "                             Regime 2 parameters                              \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const          1.7367      0.993      1.748      0.080      -0.210       3.684\n",
      "                             Regime 3 parameters                              \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const          1.9820      0.994      1.995      0.046       0.034       3.930\n",
      "                           Non-switching parameters                           \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "sigma2         0.0050      0.001      8.579      0.000       0.004       0.006\n",
      "ar.L1          2.1082      0.084     25.061      0.000       1.943       2.273\n",
      "ar.L2         -1.6909      0.202     -8.350      0.000      -2.088      -1.294\n",
      "ar.L3          0.9132      0.211      4.320      0.000       0.499       1.327\n",
      "ar.L4         -0.3374      0.094     -3.605      0.000      -0.521      -0.154\n",
      "                         Regime transition parameters                         \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "p[0->0]        0.5788        nan        nan        nan         nan         nan\n",
      "p[1->0]        0.4288      1.879      0.228      0.820      -3.254       4.112\n",
      "p[2->0]        0.3085      0.693      0.445      0.656      -1.049       1.666\n",
      "p[3->0]        0.0042        nan        nan        nan         nan         nan\n",
      "p[0->1]        0.2687        nan        nan        nan         nan         nan\n",
      "p[1->1]        0.3371        nan        nan        nan         nan         nan\n",
      "p[2->1]        0.6277        nan        nan        nan         nan         nan\n",
      "p[3->1]        0.0075      0.019      0.392      0.695      -0.030       0.045\n",
      "p[0->2]        0.1151        nan        nan        nan         nan         nan\n",
      "p[1->2]        0.1764        nan        nan        nan         nan         nan\n",
      "p[2->2]        0.0503        nan        nan        nan         nan         nan\n",
      "p[3->2]        0.0983        nan        nan        nan         nan         nan\n",
      "==============================================================================\n",
      "\n",
      "Warnings:\n",
      "[1] Covariance matrix calculated using numerical (complex-step) differentiation.\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 85464 characters]",
      "text/plain": [
       "<Figure size 700x700 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "mod_fed = sm.tsa.MarkovAutoregression(df_fed, k_regimes=4, order=4, switching_ar=False)\n",
    "res_fed = mod_fed.fit()\n",
    "\n",
    "print(res_fed.summary())\n",
    "\n",
    "# Graficar las probabilidades filtradas y suavizadas\n",
    "fig, axes = plt.subplots(2, figsize=(7, 7))\n",
    "\n",
    "# Probabilidad filtrada\n",
    "axes[0].plot(res_fed.filtered_marginal_probabilities[0])\n",
    "axes[0].set_xlim(df_fed.index[1], df_fed.index[-1])\n",
    "axes[0].set_title(\"Probabilidad Filtrada de Estado 1\")\n",
    "\n",
    "# Probabilidad suavizada\n",
    "axes[1].plot(res_fed.smoothed_marginal_probabilities[0])\n",
    "axes[1].set_xlim(df_fed.index[1], df_fed.index[-1])\n",
    "axes[1].set_title(\"Probabilidad Suavizada de Estado 1\")\n",
    "\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "comentario del ar"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "MS-DR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\NICO\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\statsmodels\\tsa\\base\\tsa_model.py:473: ValueWarning: No frequency information was provided, so inferred frequency MS will be used.\n",
      "  self._init_dates(dates, freq)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                        Markov Switching Model Results                        \n",
      "==============================================================================\n",
      "Dep. Variable:                retorno   No. Observations:                  180\n",
      "Model:               MarkovRegression   Log Likelihood                 -25.210\n",
      "Date:                Fri, 31 Jan 2025   AIC                             84.420\n",
      "Time:                        00:39:44   BIC                            138.700\n",
      "Sample:                    01-01-2010   HQIC                           106.428\n",
      "                         - 12-01-2024                                         \n",
      "Covariance Type:               approx                                         \n",
      "                             Regime 0 parameters                              \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const          0.1627      0.024      6.901      0.000       0.116       0.209\n",
      "                             Regime 1 parameters                              \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const          1.2969      0.071     18.150      0.000       1.157       1.437\n",
      "                             Regime 2 parameters                              \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const          2.2498      0.065     34.610      0.000       2.122       2.377\n",
      "                             Regime 3 parameters                              \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "const          4.9958      0.048    105.093      0.000       4.903       5.089\n",
      "                           Non-switching parameters                           \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "sigma2         0.0587      0.006      9.340      0.000       0.046       0.071\n",
      "                         Regime transition parameters                         \n",
      "==============================================================================\n",
      "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "p[0->0]        0.9860        nan        nan        nan         nan         nan\n",
      "p[1->0]        0.0573        nan        nan        nan         nan         nan\n",
      "p[2->0]     5.449e-13        nan        nan        nan         nan         nan\n",
      "p[3->0]        0.0113        nan        nan        nan         nan         nan\n",
      "p[0->1]        0.0140        nan        nan        nan         nan         nan\n",
      "p[1->1]        0.8594        nan        nan        nan         nan         nan\n",
      "p[2->1]        0.0550      0.025      2.208      0.027       0.006       0.104\n",
      "p[3->1]     1.038e-08        nan        nan        nan         nan         nan\n",
      "p[0->2]     1.067e-20        nan        nan        nan         nan         nan\n",
      "p[1->2]        0.0833      0.007     11.486      0.000       0.069       0.098\n",
      "p[2->2]        0.8963      0.062     14.383      0.000       0.774       1.018\n",
      "p[3->2]     4.174e-10        nan        nan        nan         nan         nan\n",
      "==============================================================================\n",
      "\n",
      "Warnings:\n",
      "[1] Covariance matrix calculated using numerical (complex-step) differentiation.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<Axes: title={'center': 'Probability of being in the high regime'}, xlabel='Date'>"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 27804 characters]",
      "text/plain": [
       "<Figure size 1200x300 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Fit the model\n",
    "mod_fed = sm.tsa.MarkovRegression(df_fed, k_regimes=4)\n",
    "res_fed = mod_fed.fit()\n",
    "\n",
    "print(res_fed.summary())\n",
    "\n",
    "res_fed.smoothed_marginal_probabilities[1].plot(\n",
    "    title=\"Probability of being in the high regime\", figsize=(12, 3)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "El modelo es capaz de predecir la probabilidad de cambio de régimen de la serie. En el último gráfico los cambios se régimen son ilustrados de manera más óptima."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 194,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\NICO\\AppData\\Local\\Temp\\ipykernel_18440\\883545294.py:13: UserWarning: No artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.\n",
      "  plt.legend()\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 28696 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>Ticker</th>\n",
       "      <th>SPY</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2010-01-05</th>\n",
       "      <td>0.002647</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-06</th>\n",
       "      <td>0.000704</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-07</th>\n",
       "      <td>0.004221</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-08</th>\n",
       "      <td>0.003328</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-11</th>\n",
       "      <td>0.001397</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-23</th>\n",
       "      <td>0.006222</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-27</th>\n",
       "      <td>0.014152</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-28</th>\n",
       "      <td>-0.000817</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-29</th>\n",
       "      <td>0.001279</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-30</th>\n",
       "      <td>-0.002765</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3019 rows × 1 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "Ticker           SPY\n",
       "Date                \n",
       "2010-01-05  0.002647\n",
       "2010-01-06  0.000704\n",
       "2010-01-07  0.004221\n",
       "2010-01-08  0.003328\n",
       "2010-01-11  0.001397\n",
       "...              ...\n",
       "2021-12-23  0.006222\n",
       "2021-12-27  0.014152\n",
       "2021-12-28 -0.000817\n",
       "2021-12-29  0.001279\n",
       "2021-12-30 -0.002765\n",
       "\n",
       "[3019 rows x 1 columns]"
      ]
     },
     "execution_count": 194,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import statsmodels.api as sm\n",
    "from scipy.optimize import minimize\n",
    "import statsmodels.formula.api as smf\n",
    "\n",
    "\n",
    "plt.hist(rate_sp500, bins=20, color='skyblue', edgecolor='black', alpha=0.7)\n",
    "plt.title('Histograma de los Retornos del SP500')\n",
    "plt.xlabel('Value')\n",
    "plt.ylabel('Frequency')\n",
    "plt.legend()\n",
    "plt.grid(axis='y', linestyle='--', alpha=0.6)\n",
    "plt.show()\n",
    "rate_sp500"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [],
   "source": [
    "def wp(z, p):\n",
    "    \"\"\"Función de peso según el residuo z y la probabilidad p.\"\"\"\n",
    "    return np.where(z >= 0, p * z, (p - 1) * z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 185,
   "metadata": {},
   "outputs": [],
   "source": [
    "def quantile_estimate(data, p):\n",
    "    \"\"\"Cálculo del p-ésimo cuantil usando minimización del error cuadrático ponderado.\"\"\"\n",
    "    def loss_function(beta):\n",
    "        residuals = data - beta\n",
    "        weighted_residuals = wp(residuals, p)\n",
    "        return np.sum(weighted_residuals)\n",
    "\n",
    "    # Minimización del error cuadrático ponderado sin punto de inicio\n",
    "    result = minimize(loss_function, np.mean(data))\n",
    "    return result.x[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 191,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "El 5.0% cuantil es aproximadamente: -0.016222010803018553\n"
     ]
    }
   ],
   "source": [
    "p = 0.05  # Cuantil deseado\n",
    "# Calcular el cuantil usando minimización del error cuadrático ponderado\n",
    "quantile = quantile_estimate(rate_sp500, p)\n",
    "\n",
    "print(f\"El {p*100}% cuantil es aproximadamente: {quantile}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 192,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 32568 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.hist(rate_sp500, bins=20, color='skyblue', edgecolor='black', alpha=0.7)\n",
    "plt.axvline(x=quantile, color='red', linestyle='--', label=f'{p*100}% Cuantil')\n",
    "plt.title('Histograma del SP500 con Cuantil')\n",
    "plt.xlabel('Value')\n",
    "plt.ylabel('Frequency')\n",
    "plt.legend()\n",
    "plt.grid(axis='y', linestyle='--', alpha=0.6)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 222,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>Ticker</th>\n",
       "      <th>SPY</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2010-01-05</th>\n",
       "      <td>0.002647</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-06</th>\n",
       "      <td>0.000704</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-07</th>\n",
       "      <td>0.004221</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-08</th>\n",
       "      <td>0.003328</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010-01-11</th>\n",
       "      <td>0.001397</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-23</th>\n",
       "      <td>0.006222</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-27</th>\n",
       "      <td>0.014152</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-28</th>\n",
       "      <td>-0.000817</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-29</th>\n",
       "      <td>0.001279</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-12-30</th>\n",
       "      <td>-0.002765</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3019 rows × 1 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "Ticker           SPY\n",
       "Date                \n",
       "2010-01-05  0.002647\n",
       "2010-01-06  0.000704\n",
       "2010-01-07  0.004221\n",
       "2010-01-08  0.003328\n",
       "2010-01-11  0.001397\n",
       "...              ...\n",
       "2021-12-23  0.006222\n",
       "2021-12-27  0.014152\n",
       "2021-12-28 -0.000817\n",
       "2021-12-29  0.001279\n",
       "2021-12-30 -0.002765\n",
       "\n",
       "[3019 rows x 1 columns]"
      ]
     },
     "execution_count": 222,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rate_sp500"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 243,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\NICO\\AppData\\Local\\Temp\\ipykernel_18440\\3795571230.py:1: FutureWarning: 'M' is deprecated and will be removed in a future version, please use 'ME' instead.\n",
      "  rate_sp500_monthly = (1 + rate_sp500['SPY']).resample('M').prod() - 1  # Retorno compuesto\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Date</th>\n",
       "      <th>SPY</th>\n",
       "      <th>FED</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2010-01-01</td>\n",
       "      <td>-0.052413</td>\n",
       "      <td>0.11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2010-02-01</td>\n",
       "      <td>0.031195</td>\n",
       "      <td>0.13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2010-03-01</td>\n",
       "      <td>0.060880</td>\n",
       "      <td>0.16</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2010-04-01</td>\n",
       "      <td>0.015470</td>\n",
       "      <td>0.20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2010-05-01</td>\n",
       "      <td>-0.079455</td>\n",
       "      <td>0.20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>139</th>\n",
       "      <td>2021-08-01</td>\n",
       "      <td>0.029760</td>\n",
       "      <td>0.09</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>140</th>\n",
       "      <td>2021-09-01</td>\n",
       "      <td>-0.046605</td>\n",
       "      <td>0.08</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>141</th>\n",
       "      <td>2021-10-01</td>\n",
       "      <td>0.070164</td>\n",
       "      <td>0.08</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>142</th>\n",
       "      <td>2021-11-01</td>\n",
       "      <td>-0.008035</td>\n",
       "      <td>0.08</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>143</th>\n",
       "      <td>2021-12-01</td>\n",
       "      <td>0.048891</td>\n",
       "      <td>0.08</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>144 rows × 3 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "          Date       SPY   FED\n",
       "0   2010-01-01 -0.052413  0.11\n",
       "1   2010-02-01  0.031195  0.13\n",
       "2   2010-03-01  0.060880  0.16\n",
       "3   2010-04-01  0.015470  0.20\n",
       "4   2010-05-01 -0.079455  0.20\n",
       "..         ...       ...   ...\n",
       "139 2021-08-01  0.029760  0.09\n",
       "140 2021-09-01 -0.046605  0.08\n",
       "141 2021-10-01  0.070164  0.08\n",
       "142 2021-11-01 -0.008035  0.08\n",
       "143 2021-12-01  0.048891  0.08\n",
       "\n",
       "[144 rows x 3 columns]"
      ]
     },
     "execution_count": 243,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rate_sp500_monthly = (1 + rate_sp500['SPY']).resample('M').prod() - 1  # Retorno compuesto\n",
    "\n",
    "# Cambiar la fecha al primer día del mes\n",
    "rate_sp500_monthly.index = rate_sp500_monthly.index.to_period('M').to_timestamp(how='start')\n",
    "\n",
    "# Convertir a DataFrame\n",
    "rate_sp500_monthly = rate_sp500_monthly.reset_index()\n",
    "rate_sp500_monthly.rename(columns={'rate_sp500': 'return_sp500_monthly'}, inplace=True)\n",
    "\n",
    "# Merge con la base de la FED\n",
    "df_merged = rate_sp500_monthly.merge(df_fed, on='Date', how='inner')\n",
    "\n",
    "df_merged"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 244,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Quantile 0.05\n",
      "                         QuantReg Regression Results                          \n",
      "==============================================================================\n",
      "Dep. Variable:                    SPY   Pseudo R-squared:              0.04536\n",
      "Model:                       QuantReg   Bandwidth:                     0.03913\n",
      "Method:                 Least Squares   Sparsity:                       0.4480\n",
      "Date:                Fri, 31 Jan 2025   No. Observations:                  144\n",
      "Time:                        02:09:26   Df Residuals:                      142\n",
      "                                        Df Model:                            1\n",
      "==============================================================================\n",
      "                 coef    std err          t      P>|t|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "Intercept     -0.0534      0.010     -5.169      0.000      -0.074      -0.033\n",
      "FED           -0.0152      0.013     -1.208      0.229      -0.040       0.010\n",
      "==============================================================================\n",
      "\n",
      "Quantile 0.25\n",
      "                         QuantReg Regression Results                          \n",
      "==============================================================================\n",
      "Dep. Variable:                    SPY   Pseudo R-squared:             0.006896\n",
      "Model:                       QuantReg   Bandwidth:                     0.02748\n",
      "Method:                 Least Squares   Sparsity:                       0.1175\n",
      "Date:                Fri, 31 Jan 2025   No. Observations:                  144\n",
      "Time:                        02:09:26   Df Residuals:                      142\n",
      "                                        Df Model:                            1\n",
      "==============================================================================\n",
      "                 coef    std err          t      P>|t|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "Intercept     -0.0120      0.005     -2.242      0.026      -0.023      -0.001\n",
      "FED            0.0092      0.006      1.555      0.122      -0.003       0.021\n",
      "==============================================================================\n",
      "\n",
      "Quantile 0.5\n",
      "                         QuantReg Regression Results                          \n",
      "==============================================================================\n",
      "Dep. Variable:                    SPY   Pseudo R-squared:            0.0001069\n",
      "Model:                       QuantReg   Bandwidth:                     0.03217\n",
      "Method:                 Least Squares   Sparsity:                      0.08737\n",
      "Date:                Fri, 31 Jan 2025   No. Observations:                  144\n",
      "Time:                        02:09:26   Df Residuals:                      142\n",
      "                                        Df Model:                            1\n",
      "==============================================================================\n",
      "                 coef    std err          t      P>|t|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "Intercept      0.0177      0.005      3.885      0.000       0.009       0.027\n",
      "FED            0.0002      0.005      0.031      0.975      -0.010       0.010\n",
      "==============================================================================\n",
      "\n",
      "Quantile 0.75\n",
      "                         QuantReg Regression Results                          \n",
      "==============================================================================\n",
      "Dep. Variable:                    SPY   Pseudo R-squared:             0.004983\n",
      "Model:                       QuantReg   Bandwidth:                     0.02971\n",
      "Method:                 Least Squares   Sparsity:                       0.1012\n",
      "Date:                Fri, 31 Jan 2025   No. Observations:                  144\n",
      "Time:                        02:09:26   Df Residuals:                      142\n",
      "                                        Df Model:                            1\n",
      "==============================================================================\n",
      "                 coef    std err          t      P>|t|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "Intercept      0.0382      0.005      8.061      0.000       0.029       0.048\n",
      "FED           -0.0033      0.005     -0.600      0.550      -0.014       0.008\n",
      "==============================================================================\n",
      "\n",
      "Quantile 0.95\n",
      "                         QuantReg Regression Results                          \n",
      "==============================================================================\n",
      "Dep. Variable:                    SPY   Pseudo R-squared:            0.0001869\n",
      "Model:                       QuantReg   Bandwidth:                     0.03380\n",
      "Method:                 Least Squares   Sparsity:                       0.3420\n",
      "Date:                Fri, 31 Jan 2025   No. Observations:                  144\n",
      "Time:                        02:09:26   Df Residuals:                      142\n",
      "                                        Df Model:                            1\n",
      "==============================================================================\n",
      "                 coef    std err          t      P>|t|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "Intercept      0.0698      0.009      7.945      0.000       0.052       0.087\n",
      "FED        -9.247e-05      0.012     -0.008      0.994      -0.024       0.024\n",
      "==============================================================================\n"
     ]
    }
   ],
   "source": [
    "# Ajustar un modelo de regresión por cuantiles\n",
    "quantiles = [0.05, 0.25, 0.5, 0.75, 0.95]\n",
    "models = {}\n",
    "\n",
    "for q in quantiles:\n",
    "    model = smf.quantreg(\"SPY ~ FED\", df_merged).fit(q=q)\n",
    "    models[q] = model\n",
    "    print(f\"\\nQuantile {q}\")\n",
    "    print(model.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 247,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 65108 characters]",
      "text/plain": [
       "<Figure size 1000x600 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Visualizar resultados\n",
    "plt.figure(figsize=(10, 6))\n",
    "for q in quantiles:\n",
    "    plt.plot(df_merged[\"FED\"],\n",
    "             models[q].predict(df_merged[\"FED\"]),\n",
    "             label=f\"Quantile {q}\")\n",
    "plt.scatter(df_merged[\"FED\"], df_merged[\"SPY\"], alpha=0.5, label=\"Data\")\n",
    "plt.axhline(0, color='black', linewidth=0.8, linestyle=\"--\")\n",
    "plt.axvline(0, color='black', linewidth=0.8, linestyle=\"--\")\n",
    "plt.xlabel(\"FED\")\n",
    "plt.ylabel(\"SP500\")\n",
    "plt.legend()\n",
    "plt.title(\"Quantile Regression: SP500 vs FED\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 265,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                         QuantReg Regression Results                          \n",
      "==============================================================================\n",
      "Dep. Variable:                    SPY   Pseudo R-squared:            0.0001069\n",
      "Model:                       QuantReg   Bandwidth:                     0.03217\n",
      "Method:                 Least Squares   Sparsity:                      0.08737\n",
      "Date:                Fri, 31 Jan 2025   No. Observations:                  144\n",
      "Time:                        02:19:58   Df Residuals:                      142\n",
      "                                        Df Model:                            1\n",
      "==============================================================================\n",
      "                 coef    std err          t      P>|t|      [0.025      0.975]\n",
      "------------------------------------------------------------------------------\n",
      "Intercept      0.0177      0.005      3.885      0.000       0.009       0.027\n",
      "FED            0.0002      0.005      0.031      0.975      -0.010       0.010\n",
      "==============================================================================\n",
      "      q         a         b        lb        ub\n",
      "0  0.05 -0.053449 -0.015242 -0.040185  0.009702\n",
      "1  0.15 -0.019156 -0.012115 -0.030633  0.006402\n",
      "2  0.25 -0.012042  0.009224 -0.002506  0.020954\n",
      "3  0.35  0.002874  0.001580 -0.008891  0.012050\n",
      "4  0.45  0.011568  0.001480 -0.008433  0.011394\n",
      "5  0.55  0.022576 -0.001832 -0.011768  0.008104\n",
      "6  0.65  0.028065 -0.003258 -0.013053  0.006536\n",
      "7  0.75  0.038183 -0.003280 -0.014089  0.007530\n",
      "8  0.85  0.047931 -0.005699 -0.017235  0.005836\n",
      "9  0.95  0.069806 -0.000092 -0.024236  0.024051\n",
      "{'a': np.float64(0.014724106035629942), 'b': np.float64(-0.004160022223796461), 'lb': -0.013233226795942143, 'ub': 0.004913182348349222}\n"
     ]
    }
   ],
   "source": [
    "mod = smf.quantreg(\"SPY ~ FED\", df_merged)\n",
    "res = mod.fit(q=0.5)\n",
    "print(res.summary())\n",
    "\n",
    "quantiles = np.arange(0.05, 0.96, 0.1)\n",
    "\n",
    "\n",
    "def fit_model(q):\n",
    "    res = mod.fit(q=q)\n",
    "    return [q, res.params[\"Intercept\"], res.params[\"FED\"]] + res.conf_int().loc[\n",
    "        \"FED\"\n",
    "    ].tolist()\n",
    "\n",
    "\n",
    "models = [fit_model(x) for x in quantiles]\n",
    "models = pd.DataFrame(models, columns=[\"q\", \"a\", \"b\", \"lb\", \"ub\"])\n",
    "\n",
    "ols = smf.ols(\"SPY ~ FED\", df_merged).fit()\n",
    "ols_ci = ols.conf_int().loc[\"FED\"].tolist()\n",
    "ols = dict(\n",
    "    a=ols.params[\"Intercept\"], b=ols.params[\"FED\"], lb=ols_ci[0], ub=ols_ci[1]\n",
    ")\n",
    "\n",
    "print(models)\n",
    "print(ols)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 266,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'SPY')"
      ]
     },
     "execution_count": 266,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 35580 characters]",
      "text/plain": [
       "<Figure size 800x600 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "x = np.arange(df_merged.FED.min(), df_merged.FED.max(), 50)\n",
    "get_y = lambda a, b: a + b * x\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(8, 6))\n",
    "\n",
    "for i in range(models.shape[0]):\n",
    "    y = get_y(models.a[i], models.b[i])\n",
    "    ax.plot(x, y, linestyle=\"dotted\", color=\"grey\")\n",
    "\n",
    "y = get_y(ols[\"a\"], ols[\"b\"])\n",
    "\n",
    "ax.plot(x, y, color=\"red\", label=\"OLS\")\n",
    "ax.scatter(df_merged.FED, df_merged.SPY, alpha=0.2)\n",
    "ax.set_xlim((-.1, 3))\n",
    "ax.set_ylim((-.1, .20))\n",
    "legend = ax.legend()\n",
    "ax.set_xlabel(\"FED\", fontsize=16)\n",
    "ax.set_ylabel(\"SPY\", fontsize=16)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### CONCLUSIONES Y VALOR PARA LA INDUSTRIA"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Toma de decisiones más informada: La integración de modelos no lineales y análisis cuánticos permite anticipar movimientos de mercado con mayor precisión, resultando en estrategias de inversión mejor calibradas.\n",
    "2. Optimización de la gestión crediticia: La adopción de modelos de clasificación (Logit y Discriminante Lineal) respalda políticas de crédito más eficientes, al identificar con rapidez emisores o contrapartes con mayor probabilidad de deterioro.\n",
    "3. Riesgo en perspectiva: El uso combinado de VaR, Montecarlo y regímenes de volatilidad aporta una visión holística del riesgo, facilitando políticas de cobertura proactivas en entornos cambiantes.\n",
    "4. Escalabilidad y adaptabilidad: Estos enfoques se pueden ampliar a otros mercados, productos financieros o indicadores macro, convirtiéndose en una base sólida para desarrollar soluciones personalizadas en gestión de riesgo y previsión de mercados."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ¿Quieres implementar estas soluciones en tu organización?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Si tu institución necesita optimizar procesos de análisis financiero, robustecer la gestión del riesgo o modernizar sus métodos de evaluación crediticia, podemos diseñar soluciones a la medida, basadas en metodologías probadas y tecnología de punta.\n",
    "\n",
    "Contacto\n",
    "\n",
    "Correo: willaysolutions@info.com\n",
    "\n",
    "willaysolutions.com"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 295104 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {
      "image/png": {
       "width": 800
      }
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "display(Image(filename='Info Willay.png', width=800))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
